/*
 * uploadFile.js 基于HTML5 文件上传的核心脚本
 */

var uploadFile = {
    fileInput: null,				//html file控件
    dragDrop: null,				//拖拽敏感区域
    upButton: null,				//提交按钮
    url: "",						//ajax地址
    fileFilter: [],				//过滤后的文件数组
    backFileUrl:[],               //多次上传成功后的所有文件（图片）地址
    filter: function(files) {		//选择文件组的过滤方法
        return files;
    },
    onSelect: function() {},		//文件选择后
    onDelete: function() {},		//文件删除后
    onExistsDelete:function () {}, //存在文件删除后
    onDragOver: function() {},		//文件拖拽到敏感区域时
    onDragLeave: function() {},	//文件离开到敏感区域时
    onProgress: function() {},		//文件上传进度
    onSuccess: function() {},		//文件上传成功时
    onFailure: function() {},		//文件上传失败时,
    onComplete: function() {},		//文件全部上传完毕时

    /* 开发参数和内置方法分界线 */

    //文件拖放
    funDragHover: function(e) {
        e.stopPropagation();
        e.preventDefault();
        this[e.type === "dragover"? "onDragOver": "onDragLeave"].call(e.target);
        return this;
    },
    //获取选择文件，file控件或拖放
    funGetFiles: function(e) {
        // 取消鼠标经过样式
        this.funDragHover(e);

        // 获取文件列表对象
        var files = e.target.files || e.dataTransfer.files;
        //继续添加文件
        this.fileFilter = this.fileFilter.concat(this.filter(files));
        this.funDealFiles();
        return this;
    },

    //选中文件的处理与回调
    funDealFiles: function() {
        for (var i = 0, file; file = this.fileFilter[i]; i++) {
            //增加唯一索引值
            file.index = i;
        }
        //执行选择回调
        this.onSelect(this.fileFilter);
        return this;
    },

    //删除对应的文件
    funDeleteFile: function(fileDelete) {
        var arrFile = [];
        for (var i = 0, file; file = this.fileFilter[i]; i++) {
            if (file != fileDelete) {
                arrFile.push(file);
            } else {
                this.onDelete(fileDelete);
            }
        }
        this.fileFilter = arrFile;
        return this;
    },
    //删除对应的已上传的文件
    existsDeleteFile:function (fileUrl,index) {
        var arrFileUrl=[];
        for(var j=0,thisFile;thisFile=this.backFileUrl[j];j++){
            if(thisFile!=fileUrl){
                arrFileUrl.push(thisFile);
            }else{
                this.onExistsDelete(thisFile,index);
            }
        }
        this.backFileUrl = arrFileUrl;
        return this;
    },

    //文件上传
    funUploadFile: function() {

        var self = this;
        var client = new OSS.Wrapper({
            region: 'oss-cn-shenzhen',
            accessKeyId: 'LTAImVBCIWgaWXav',
            accessKeySecret: 'DWYPPxaxgvGm30yFn0BYB8ABRJjDKL',
            bucket: 'vimi8-dev'
        });

        if (location.host.indexOf("sitepointstatic") >= 0) {
            //非站点服务器上运行
            return;
        }
        var zhezhao=document.getElementById("zhezhao");
        zhezhao.style.display="block";
        document.body.style.height="100%";
        document.body.style.overflow="hidden";
        var urlList=[];
        var strUrls="";
        if(!this.fileFilter.length){
            zhezhao.style.display="none";
            document.body.style.height="";
            document.body.style.overflow="";
            ShowTip("没有图片或者图片已被删除！", "danger", 2000);
            return;
        }
        for (var i = 0, file; file = this.fileFilter[i]; i++) {
            (function(file) {
                var xhr = new XMLHttpRequest();
                var storeAs = "farmImg/"+getUuid()+".jpg";
                // 开始上传
                client.multipartUpload(storeAs, file).then(function (result) {
                    var uploadPath="http://vimi8-dev.oss-cn-shenzhen.aliyuncs.com/"+result.name;
                    self.backFileUrl.push(uploadPath);
                    strUrls+=(uploadPath+",");
                    console.log(result);
                    console.log(uploadPath);
                    self.onSuccess(file, uploadPath);
                    self.funDeleteFile(file);
                    if (!self.fileFilter.length) {
                        zhezhao.style.display="none";
                        document.body.style.height="";
                        document.body.style.overflow="";
                        //全部完毕
                        self.onComplete(self.backFileUrl,strUrls);
                    }
                    //$("[name=img]").attr("src",uploadPath);
                }).catch(function (err) {
                    zhezhao.style.display="none";
                    document.body.style.height="";
                    document.body.style.overflow="";
                    self.onFailure(file, err);
                    console.log(err);
                });
            })(file);

        }

        function getUuid(){
            var len=32;//32长度
            var radix=16;//16进制
            var chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid=[],i;radix=radix||chars.length;if(len){for(i=0;i<len;i++)uuid[i]=chars[0|Math.random()*radix];}else{var r;uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';uuid[14]='4';for(i=0;i<36;i++){if(!uuid[i]){r=0|Math.random()*16;uuid[i]=chars[(i==19)?(r&0x3)|0x8:r];}}}
            return uuid.join('');
        }

    },


    init: function() {
        var self = this;

        if (this.dragDrop) {
            this.dragDrop.addEventListener("dragover", function(e) { self.funDragHover(e); }, false);
            this.dragDrop.addEventListener("dragleave", function(e) { self.funDragHover(e); }, false);
            this.dragDrop.addEventListener("drop", function(e) { self.funGetFiles(e); }, false);
        }

        //文件选择控件选择
        if (this.fileInput) {
            this.fileInput.addEventListener("change", function(e) { self.funGetFiles(e); }, false);
        }

        //上传按钮提交
        if (this.upButton) {
            this.upButton.addEventListener("click", function(e) { self.funUploadFile(e); }, false);
        }

    }
};
